<script setup>

import { reactive, toRefs, onMounted, ref } from 'vue'
import api from '@/api'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'

const router = useRouter()

const user = useUserStore()
user.loadList()


const tableData = ref([])
const originData = ref([])

const nameData = ref([])
const supplierData = ref([])

const paramList = ref([])
const paramForm = reactive({})

const data = reactive({
    drawer: false,
    formSearch: {
        class: '',
        name: '',
    },
    formData: {
        id: '',
        nId: '',
        nName: '',
        cName: '',
        cmName: '',
        sName: '',
        sId: '',
        name: '',
        safetySymbol: '',
        unit: ''
    }
})

const onSubmit = () => {

    if(tableRef.value) {
        data.formData.id = ''
        tableRef.value.setCurrentRow()
    }
    return new Promise((resolve, reject) => {
        api.post('api/comp/modelList', {
            'name': ''
        }).then(res => {

            originData.value = res.d

            for(let d of originData.value) {
                d.param = d.modelParamList.map(i => i.pName).join(',')
            }
            fillTable(page.value)
            resolve()
        })
    })

}

const submit = state => {
    console.log(state)
    switch (state) {
        case 0:
            api.post('api/comp/modelEdit', {
                ...data.formData,
                params: paramList.value.map(i => ({'pId': i.pId, 'message': paramForm[i.pId]}))
            })
                .then(res => {
                    if (res.c === 0) {
                        ElMessage({
                            message: '添加成功',
                            type: ''
                        })
                    } else {
                        ElMessage({
                            message: res.m,
                            type: 'error'
                        })
                    }
                })
            break
        case 1:
            api.post('api/comp/modelEdit', {
                ...data.formData,
                params: paramList.map(i => ({'pId': i.pId, 'message': paramForm[i.pId]}))
            })
                .then(res => {
                    if (res.c === 0) {
                        ElMessage({
                            message: '修改成功',
                            type: ''
                        })
                    } else {
                        ElMessage({
                            message: res.m,
                            type: 'error'
                        })
                    }
                })
            break
        case 2:
            api.post('api/comp/modelDel', data.formData)
                .then(res => {
                    if (res.c === 0) {
                        ElMessage({
                            message: '删除成功',
                            type: ''
                        })
                    } else {
                        ElMessage({
                            message: res.m,
                            type: 'error'
                        })
                    }
                })
            break
        default:
            break
    }
}




const handleSelectName = item => {
    data.formData.nId = item.id
    data.formData.cName = item.cName
    data.formData.unit = item.unit



    console.log(item, paramForm, paramList)

    paramList.value = item.nameParamDTOList
    item.nameParamDTOList.forEach(i => {
        paramForm[i.pId] = ''
    })
}

const querySearchName = (str, cb) => {
    api.post('api/comp/emNamelList', {'pym': str})
    .then(res => {
        cb(res.d.map(i => ({...i, 'value': i.name})))

    })
}
const handleSelectSupplier = item => {
    data.formData.sId = item.id
}

const querySearchSupplier = (str, cb) => {
    api.post('api/comp/supplierList', {'pym': str, 'page': '1', 'pageSize': Number.MAX_SAFE_INTEGER})
    .then(res => {
        cb(res.d.records.map(i => ({...i, 'value': i.name})))
    })
}
const handleSelectClassModel = item => {
    data.formData.cmId = item.id
}

const querySearchClassModel = (str, cb) => {
    api.post('api/comp/classModelList', {'pym': str})
    .then(res => {
        cb(res.d.map(i => ({...i, 'value': i.name})))
    })
}


const numberPerPage = 10

const disabledPre = computed(() => (page.value === 1))
const disabledNext = computed(() => (page.value * numberPerPage >= originData.value.length))

const
    page = ref(1)

const nextPage = () => {
    page.value ++

    fillTable(page.value)
}

const prePage = () => {
    page.value --

    fillTable(page.value)
}

// 这里要用深拷贝 否则 data和tableData 会同时改变
const fillTable = num => {
    tableData.value = JSON.parse(JSON.stringify([].slice.call(originData.value, (num - 1) * numberPerPage, num * numberPerPage)))
    // for(let d of tableData.value) {
    //     if(d.code.length > 7) {
    //         d.code = d.code.slice(0, 7) + '...'
    //     }
    //     if(d.supplier.length > 7) {
    //         d.supplier = d.supplier.slice(0, 7) + '...'
    //     }
    // }
}

const tableRef = ref()

const handleCurrentChange = (currentRow, oldCurrentRow) => {
    if(currentRow) {
        data.formData = currentRow
        paramList.value = currentRow.modelParamList
        currentRow.modelParamList.forEach(i => {paramForm[i.pId] = i.pMessage})
        api.post('api/comp/supplierModelList', {'mId': currentRow.id})
        .then(res => {
            data.formData.sId = res.d[0].sId
            data.formData.sName = res.d[0].sName
        })
    } else {
        data.formData = {
            id: '',
            nId: '',
            nName: '',
            cName: '',
            cmName: '',
            sName: '',
            sId: '',
            name: '',
            safetySymbol: '',
            unit: ''
        }
        paramForm = {}
        paramList.value = []
    }
}

const onDblClick = rtr => {
    router.push(rtr)
}

onSubmit()

const { formSearch, formData, drawer } = toRefs(data)

</script>

<template>
    <div model="content">
        <page-main>
            <div id="form">
                <div>
                    <el-form :inline="true" :model="formSearch" model="demo-form-inline" size="mini">

                        <el-form-item label="设备型号">
                            <el-input  v-model="formSearch.name" style="width: 80px" placeholder="输入名称" />
                        </el-form-item>
                        <el-form-item label="设备分类">
                            <el-input  v-model="formSearch.class" style="width: 80px" placeholder="输入名称" />
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="onSubmit">查询</el-button>
                        </el-form-item>
                    </el-form>
                </div>

                <el-table
                    ref="tableRef"
                    :data="tableData" :cell-style="rowmodel"
                    style="width: 830px;height:350px;font-size: 10px;"
                    highlight-current-row
                    @current-change="handleCurrentChange"
                >
                    <el-table-column
                        fixed
                        prop="cName"
                        label="设备分类"
                        width="80px"
                    />
                    <el-table-column
                        fixed
                        prop="cmName"
                        label="型号分类"
                        width="120px"
                    />
                    <el-table-column
                        fixed
                        prop="nName"
                        label="设备名称"
                        width="120px"
                    />
                    <el-table-column
                        fixed
                        prop="name"
                        label="设备型号"
                        width="200px"
                    />
                    <el-table-column
                        fixed
                        prop="param"
                        label="参数"
                        width="300px"
                    />
                </el-table>

                <div :style="{height: '100px', width: '100%', position: 'relative'}">
                    <div style="height: 30px;
                    width: 240px;
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    margin: auto;

                    font-size: 8px;">
                        <span>第&nbsp;{{page}}&nbsp;页</span>
                        <span>共&nbsp;{{ Math.ceil(originData.length / numberPerPage) }}&nbsp;页   </span>


                        <el-button-group>
                            <el-button type="primary" @click="prePage" :disabled="disabledPre">上页</el-button>
                            <el-button type="primary" @click="nextPage" :disabled="disabledNext">下页</el-button>
                        </el-button-group>
                    </div>
                </div>

                <!-- <el-button type="primary" style="margin-top: 20px;" @click="drawer = true">设备型号操作</el-button> -->

                <!-- <el-drawer
                    v-model="drawer"
                    title="操作"
                    direction="rtl"
                    custom-model="demo-drawer"
                    size="30%"
                > -->
                <el-card style="margin-top: 40px;">
                    <el-form
                        label-position="left"
                        label-width="100px"
                        >

                            <el-form-item label="设备名称" @dblclick.native="onDblClick('/emName')">
                                <el-autocomplete
                                    v-model="formData.nName"
                                    :fetch-suggestions="querySearchName"
                                    @select="handleSelectName"
                                    />
                            </el-form-item>

                            <el-form-item label="设备分类">
                                <el-input  v-model="formData.cName" disabled />
                            </el-form-item>
                            <el-form-item label="单位">
                                <el-input  v-model="formData.unit" disabled />
                            </el-form-item>
                            <el-form-item label="供应商" @dblclick.native="onDblClick('/others/supplier')">
                                <el-autocomplete
                                    v-model="formData.sName"
                                    :fetch-suggestions="querySearchSupplier"
                                    @select="handleSelectSupplier"
                                    />
                            </el-form-item>
                            <el-form-item label="设备型号">
                                <el-input  v-model="formData.name" />
                            </el-form-item>
                            <el-form-item label="型号分类">
                                <el-autocomplete
                                    v-model="formData.cmName"
                                    :fetch-suggestions="querySearchClassModel"
                                    @select="handleSelectClassModel"
                                    />
                            </el-form-item>
                            <el-form-item label="安全标识">
                                <el-input  v-model="formData.safetySymbol" />
                            </el-form-item>
                            <el-form-item label="生产许可证">
                                <el-input  v-model="formData.productionLicense" />
                            </el-form-item>

                            <el-divider />

                            <div v-for="param in paramList" :key="param.id">
                                <el-form-item :label="param.pName + '：'">
                                    <el-input  v-model="paramForm[param.pId]" style="width: 200px;" placeholder="请输入参数" />
                                </el-form-item>
                            </div>

                            <el-divider />

                            <el-form-item>
                                <el-button type="primary" :loading="loading" :disabled="(data.formData.id !== '')" @click="submit(0)">增&nbsp;&nbsp;&nbsp;&nbsp;加</el-button>
                                <el-button :loading="loading" :disabled="(data.formData.id === '')" @click="submit(1)">修&nbsp;&nbsp;&nbsp;&nbsp;改</el-button>
                                <el-button :loading="loading" :disabled="(data.formData.id === '')" @click="submit(2)">删&nbsp;&nbsp;&nbsp;&nbsp;除</el-button>
                            </el-form-item>
                    </el-form>
                <!-- </el-drawer> -->
                </el-card>
            </div>
        </page-main>
    </div>
</template>

<style>

</style>
